package com.niiwoo.civet.account.listener;/**
 * Created by DELL on 2017/12/9.
 */

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.constant.MQConstant;
import com.niiwoo.civet.account.dto.request.WithdrawAuditMQMsg;
import com.niiwoo.civet.account.service.local.withdraw.WithdrawService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 提现MQ消费
 *
 * @author xiaoyingping
 * @create 2017-12-09 11:00
 **/
@Component
@Slf4j
public class WithdrawListener {

    @Autowired
    private WithdrawService withdrawService;

    /**
     * 监听提现审批消息
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {MQConstant.WITHDRAW_AUDIT_DATA_QUEUE})
    public void listenerWithdrawAudit(Message message, Channel channel) throws IOException {
        String messageBody = new String(message.getBody(), "UTF-8");
        log.info("提现审批MQ消息:{}", messageBody);
        try {
            //从消息中取出消息
            WithdrawAuditMQMsg withdrawAuditMQMsg = JSON.parseObject(messageBody, WithdrawAuditMQMsg.class);
            if(withdrawAuditMQMsg.getIsAuditPass()){
                //提现审批通过
                withdrawService.confirmWithdraw(withdrawAuditMQMsg.getWithdrawOrderId());
            }else {
                //提现审批拒绝
                withdrawService.cancelWithdraw(withdrawAuditMQMsg.getWithdrawOrderId());
            }
        } catch (Exception e) {
            log.error("提现审批MQ消息消费异常:{}", messageBody,e);
        } finally {
            log.info("提现审批MQ消息ACK:{}", messageBody);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }

}
